from typing import Dict, Any
import requests
import pandas as pd
from agents.components.base import BaseComponent, ComponentConfig, ComponentType

class HttpComponent(BaseComponent):
    """HTTP服务组件实现"""
    
    @classmethod
    def get_component_type(cls) -> ComponentType:
        """获取组件类型"""
        return ComponentType.HTTP
    
    @classmethod
    def get_component_name(cls) -> str:
        """获取组件名称"""
        return "http_component"
    
    @classmethod
    def get_component_description(cls) -> str:
        """获取组件描述"""
        return "用于执行HTTP请求的组件，支持GET、POST等请求方法，可配置base_url、headers等参数"
    
    @classmethod
    def get_config_schema(cls) -> Dict[str, Any]:
        """获取配置schema"""
        return {
            "type": "object",
            "properties": {
                "base_url": {
                    "type": "string",
                    "description": "基础URL"
                },
                "headers": {
                    "type": "object",
                    "description": "请求头"
                },
                "timeout": {
                    "type": "integer",
                    "description": "请求超时时间(秒)"
                },
                "convert_to_dataframe": {
                    "type": "boolean",
                    "description": "是否将响应转换为DataFrame"
                }
            },
            "required": ["base_url"]
        }
    
    @classmethod
    def get_input_schema(cls) -> Dict[str, Any]:
        """获取输入schema"""
        return {
            "type": "object",
            "properties": {
                "method": {
                    "type": "string",
                    "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"],
                    "description": "HTTP请求方法"
                },
                "endpoint": {
                    "type": "string",
                    "description": "API端点"
                },
                "params": {
                    "type": "object",
                    "description": "URL参数"
                },
                "data": {
                    "type": "object",
                    "description": "请求体数据"
                }
            },
            "required": ["endpoint"]
        }
    
    @classmethod
    def get_output_schema(cls) -> Dict[str, Any]:
        """获取输出schema"""
        return {
            "type": "object",
            "properties": {
                "data": {
                    "type": ["object", "array"],
                    "description": "响应数据"
                },
                "error": {
                    "type": "string",
                    "description": "错误信息"
                },
                "status_code": {
                    "type": "integer",
                    "description": "HTTP状态码"
                }
            }
        }
    
    def __init__(self, config: ComponentConfig):
        super().__init__(config)
        self.base_url = config.config.get("base_url", "")
        self.headers = config.config.get("headers", {})
        self.timeout = config.config.get("timeout", 30)
        
    async def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """执行HTTP请求"""
        try:
            # 获取请求配置
            method = input_data.get("method", "POST")
            endpoint = input_data.get("endpoint", "")
            params = input_data.get("params", {})
            data = input_data.get("data", {})
            
            # 构建完整URL
            url = f"{self.base_url}{endpoint}"
            
            # 发送请求
            response = requests.request(
                method=method,
                url=url,
                params=params,
                json=data,
                headers=self.headers,
                timeout=self.timeout
            )
            
            # 检查响应状态
            response.raise_for_status()
            
            # 解析响应数据
            result = response.json()
            
            # 如果配置了转换为DataFrame
            if self.config.config.get("convert_to_dataframe", False):
                if isinstance(result, dict) and "rows" in result:
                    result = pd.DataFrame(result["rows"])
                elif isinstance(result, list):
                    result = pd.DataFrame(result)
            
            return {"data": result}
            
        except requests.exceptions.RequestException as e:
            return {
                "error": str(e),
                "status_code": getattr(e.response, "status_code", None) if hasattr(e, "response") else None
            }
    
    def validate_input(self, input_data: Dict[str, Any]) -> bool:
        """验证输入数据"""
        required_fields = self.config.input_schema.get("required", [])
        return all(field in input_data for field in required_fields)
    
    def validate_output(self, output_data: Dict[str, Any]) -> bool:
        """验证输出数据"""
        return "data" in output_data or "error" in output_data 